import React, { useEffect, useState } from 'react';
import { Button, Row, Col, Drawer, Grid, Menu, message } from 'antd';
import styles from './index.less';
import { Link, history, useModel, KeepAliveLayout } from 'umi';
import { Scrollbars } from 'react-custom-scrollbars';
import { Decrypt, Encrypt } from '@/utils/encryp';
import RightContent from '@/components/RightContent';
import { MenuOutlined } from '@ant-design/icons';
import subroutes from '../../config/subroutes';
import { useMemo } from 'react';
import { useAsyncEffect } from 'ahooks';
import { getFetch } from '@/utils/doFetch';

const { SubMenu } = Menu;

let col = { xs: 4, sm: 4, md: 4, lg: 4, xl: 5, xxl: 6 },
  cols = { xs: 20, sm: 20, md: 20, lg: 20, xl: 19, xxl: 18 };
const { useBreakpoint } = Grid;

let BasicLayout = (props) => {
  const screens = useBreakpoint(),
    { children, location } = props;
  const [visible, setVisible] = useState(false);
  const { initialState, setInitialState } = useModel('@@initialState');
  const onClose = () => {
    setVisible(false);
  };

  let handleClick = (e) => {
    history.push(e.key);
  };

  useAsyncEffect(async () => {
    let params = location.query;
    console.log(params);
    if (params?.token) {
      localStorage.setItem('TOKEN', params.token);
      return;
    }
    const currentUser = await getFetch({ url: '/vehicle-api/user/info' });
    setInitialState((s) => ({
      ...s,
      currentUser: currentUser.data ?? {},
    }));
  }, [location.pathname]);

  let menus = useMemo(() => {
    if (initialState?.currentUser?.menus && initialState?.currentUser?.menus.length > 0) {
      let res = initialState?.currentUser?.menus
        .filter((it) => it.menu_type == 'pc')
        .map((it) => {
          return {
            path: '/' + it.menu_key,
            name: it.name,
          };
        });
      let sub = res.filter((it) => !it.path.includes('system')),
        end = res.filter((it) => it.path.includes('system'));

      return [...sub, ...end];
    } else {
      return [];
    }
  }, [initialState?.currentUser]);

  return (
    <div className={styles.container}>
      <Row style={{ height: 48, background: '#071017' }}>
        <Col
          {...col}
          style={{ backgroundImage: `url(${require('@/assets/headerbg_l.png')})`, height: 48 }}
          className={styles.imgl}
        >
          <div className="center" style={{ height: '100%', paddingLeft: 12 }}>
            <img
              style={{ width: 'auto', height: 24, marginTop: -2, marginRight: 12, marginLeft: 8 }}
              src={require('@/assets/logo_simple.png')}
              alt=""
            />
            {screens.lg && (
              <div style={{ flex: 1 }}>
                <img
                  style={{ width: '100%', maxWidth: 280 }}
                  src={require('@/assets/title_simple.png')}
                  alt=""
                />
              </div>
            )}
          </div>
        </Col>
        <Col
          {...cols}
          style={{ backgroundImage: `url(${require('@/assets/headerbg_r.png')})`, height: 48 }}
          className={styles.imgr}
        >
          <div
            className="center"
            style={{
              height: '100%',
              paddingLeft: 30,
              justifyContent: 'space-between',
              alignItems: 'center',
            }}
          >
            {screens.lg && (
              <ul className={styles.menu}>
                {menus ////menus
                  .filter((it) => it.name)
                  .map((it, i) => (
                    <Link
                      key={i}
                      to={it.path}
                      className={location.pathname.indexOf(it.path) != -1 ? styles.button : ' '}
                    >
                      <span
                        style={{
                          fontSize: screens.xl ? 14 : 12,
                          display: 'block',
                          height: 20,
                          lineHeight: '20px',
                          textAlign: 'center',
                        }}
                      >
                        {it.name}
                      </span>
                    </Link>
                  ))}
              </ul>
            )}

            <div
              className="center"
              style={{
                paddingTop: !screens.lg ? 8 : 0,
                justifyContent: !screens.lg ? 'flex-end' : 'space-between',
                width: !screens.lg ? '100%' : 'auto',
              }}
            >
              <RightContent></RightContent>
              {!screens.lg && (
                <div
                  className="center"
                  style={{
                    borderRadius: 4,
                    backgroundColor: '#0fbebc',
                    padding: 6,
                    marginRight: 12,
                  }}
                  onClick={() => {
                    setVisible(true);
                  }}
                >
                  <MenuOutlined style={{ color: '#fff' }} />
                </div>
              )}
            </div>
          </div>
        </Col>
      </Row>
      <div className={styles.mainbg}>
        <KeepAliveLayout {...props} style={{ width: '100%', height: 'calc(100vh - 56px)' }}>
          <Scrollbars
            thumbMinSize={10}
            autoHide
            style={{ width: '100%', height: 'calc(100vh - 56px)' }}
            hideTracksWhenNotNeeded={true}
          >
            {children}
          </Scrollbars>
        </KeepAliveLayout>
      </div>
      <Drawer placement="right" onClose={onClose} visible={visible}>
        <Menu
          theme={'dark'}
          onClick={handleClick}
          style={{ width: '100%' }}
          selectedKeys={[location.pathname]}
          mode="inline"
        >
          {menus.map((it) => {
            if (!it.name) {
              return;
            }
            if (!it.routes) {
              return <Menu.Item key={it.path}>{it.name}</Menu.Item>;
            } else {
              return (
                <SubMenu key={it.path} title={it.name}>
                  {it.routes.map((item) => {
                    if (!item.name) {
                      return;
                    }
                    return <Menu.Item key={item.path}>{item.name}</Menu.Item>;
                  })}
                </SubMenu>
              );
            }
          })}
        </Menu>
      </Drawer>
    </div>
  );
};

export default BasicLayout;
